using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace csharp.common
{
    public class LogErro
    {
        private static string nameFile= System.Windows.Forms.Application.StartupPath+"\\log\\errors.xml";
        private static string sqlFile = System.Windows.Forms.Application.StartupPath+"\\log\\sqlerros.xml";
        private static int cont;

        public static void writeError(string msg)
        {
            writeFile(nameFile, msg);
        }


        public static void writeErrorSql(string msg)
        {
            writeFile(sqlFile, msg);
        }


        public static void writeFile(string file, string msg)
        {
            string temp;
            
            cont =0;
            try
            {
	            temp = "-------------------------------------------------------------------------------------------------";
	            temp+= "\nData: "+DateTime.Now.ToLongDateString();
	            temp+= "\nHora: "+DateTime.Now.ToLongTimeString();
	            temp+= "\n-------------------------------------------------------------------------------------------------";
	            temp+= "\n"+msg;
	            temp+= "\n-------------------------------------------------------------------------------------------------\n\n";
	            
	            Stream stFile = File.Open(file, FileMode.Append);
	            StreamWriter swFile = new StreamWriter(stFile);
	
	            swFile.WriteLine(temp);
	            swFile.Flush();
	            swFile.Close();	
            }
            catch(DirectoryNotFoundException)
            {
            	Directory.CreateDirectory(file.Substring(0, file.LastIndexOf("\\")));
            	cont++;
            	
            	if (cont < 3)
            		writeFile(nameFile, msg);
            }
            catch(FileNotFoundException)
            {
            	cont++;
            	
            	//Tenta 3 vezes
            	if (cont < 3)
            		writeFile("errors.xml", msg);
            }
        }
    }
}
